package com.njbw.websocket.config;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * 在 WebSocket 中做鉴权需要怎么进行拦截呢？websocket 为我们提供了一个类
 */
@Component
public class WebSocketServerConfig extends ServerEndpointConfig.Configurator {

    // 鉴权需要重写该方法
    @Override
    public boolean checkOrigin(String originHeaderValue) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 取连接参数进行校验
        // 校验逻辑 通过 return true；不通过 return false
        return true;
    }

    // 一些 webSocket 连接需要传递一些参数，想要知道谁传递的
    // 此处可以通过 HandshakeRequest 拿到一些连接数据
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> parameterMap = request.getParameterMap();
        List<String> erpList = parameterMap.get("erp");
        if (!CollectionUtils.isEmpty(erpList)) {
            sec.getUserProperties().put("erp", erpList.get(0)); // 后续我们就可以拿到这里设置的值做各种各样的操作
        }
        super.modifyHandshake(sec, request, response);
    }
}
